package com.xu.ai.model.openai.controller;

import java.util.List;
import java.util.Map;

import org.springframework.ai.document.Document;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.filter.FilterExpressionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * MariaDB Vector 是 MariaDB 11.7 的一部分，支持存储和搜索机器学习生成的嵌入。
 * 它利用向量索引提供了高效的向量相似性搜索能力，支持余弦相似度和欧几里得距离度量。
 *
 * @author xuguan
 * @since 2025/9/18
 */
@RestController
@RequestMapping("/api/vector")
public class VectorStoreController {

	@Autowired
	private VectorStore vectorStore;

	@PostMapping(path = "/add")
	public void addVector() {
		Document document1 = new Document("Mike是一名Java开发工程师, 目前正在学习spring ai和spring ai alibaba",
				Map.of("name", "Mike", "job", "Java开发工程师", "learning", "spring ai和spring ai alibaba"));
		Document document2 = new Document("Mike喜欢写代码",
				Map.of("name", "Mike", "like", "coding"));
		Document document3 = new Document("Mike不喜欢上班",
				Map.of("name", "Mike", "unlike", "work"));
		vectorStore.add(List.of(document1, document2, document3));
	}

	@PostMapping(path = "/upload")
	public void uploadVector(@RequestParam("data") MultipartFile data) {
		TextReader reader = new TextReader(data.getResource());
		final List<Document> documents = TokenTextSplitter.builder().build().split(reader.read());
		vectorStore.add(documents);
	}

	@GetMapping(path = "/search")
	public List<Document> searchVector(@RequestParam("query") String query) {
		final SearchRequest searchRequest = SearchRequest.builder()
				.query(query)
				// .filterExpression(new FilterExpressionBuilder().eq("name", "Mike").build())
				.similarityThreshold(0.5d) // 相似度阈值0.5
				.topK(3) // 返回前3个结果
				.build();
		return vectorStore.similaritySearch(searchRequest);
	}

	@DeleteMapping(path = "/delete-by-id")
	public void deleteVectorById(@RequestParam("id") List<String> id) {
		vectorStore.delete(id);
	}

	@DeleteMapping(path = "/delete-by-filter")
	public void deleteVectorByFilter(@RequestParam("name") String name) {
		vectorStore.delete(new FilterExpressionBuilder().eq("name", name).build());
	}
}
